<?php

namespace App\Http\Controllers\Home;

use App\Models\Configs;
use App\Models\IntegralLogs;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;
//    use Socialite;

    /**
     * 用户登录
     * @param Request $request
     * @return bool
     */
    public function login(Request $request)
    {
        if($request->method() == 'POST'){
            $data = [
                'mobile' => (string)$request->post('mobile'),
                'password' => (string)$request->post('password'),
            ];
            $user_type = (int)$request->post('user_type',2);// 1密码登陆 2手机验证码登录
            if ($user_type == 1){
            	//验证
                $rules = ['mobile' => 'required', 'password' => 'required',];
                $msgs = ['mobile.required' => '请填写手机号码', 'password.required' => '请填写密码',];
                $validator = validator()->make($data,$rules,$msgs);
                if ($validator->fails()) {
                    return $this->writeJson(1,null,$validator->errors()->first());
                }
            }
            //存缓存
            $auth = false;
            if($user_type == 2 && $data['password'] == null) {
                $auth = auth()->guard('web')->attempt(['mobile' => $data['mobile']]);
            }else {
                $auth = auth()->guard('web')->attempt(['mobile' => $data['mobile'],'password' => $data['password']]);
            }
            //存缓存
            if ($auth) {
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $users = auth()->guard('web')->user();
                if($users['status'] == -1){
                    return $this->writeJson(1,null,'当前用户不存在');
                }
                //当天第一次登陆送积分
                if (trim(@date('Y-m-d', strtotime($users['login_at']))) != trim(date('Y-m-d'))) {
                    $integral = Configs::getConfig('integral');
                    if($users['type'] == 1) {//HR登陆送积分
                        $integral_login = $integral['hr_login'];
                    }elseif ($users['type'] == 2) {//供应商登陆送积分
                        $integral_login = $integral['bus_login'];
                    }
                    Users::where('id',$users['id'])->increment('integral',$integral_login);
                    //添加日志记录
                    $integral = [
                        'user_id' => $users['id'],
                        'user_name' => $users['username'],
                        'integral' => '+'.$integral_login,
                        'desc' => '每日首次登陆送积分',
                        'type' => 1,
                    ];
                    IntegralLogs::create($integral);
                }
                Users::where('id',$users['id'])->update(['login_at' => date('Y-m-d H:i:s'), 'login_ip' => $request->ip()]);
                return $this->writeJson(0,$users,'登录成功');
            }
            return $this->writeJson(1,null,'用户名或密码错误');
        }else{
            return view('home.login.login');
        }
    }

    /**
     * 找回密码
     * @param Request $request
     * @return bool
     */
    public function findPass(Request $request)
    {
        if($request->method() == 'POST'){
            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            $confirmc_pass = (string)$request->post('confirmc_pass');
            if(empty($mobile) || empty($password) || empty($confirmc_pass))  return $this->writeJson(1,null,'手机号码不能为空');
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $mobile)) return $this->writeJson(1,null,'请填写正确的手机号码');
            if($password !== $confirmc_pass){
                return $this->writeJson(1,null,'两次密码输入不一致,请重新输入');
            }

            $info = Users::where('mobile',$mobile)->first(['id','status']);
            if(!empty($info) && $info['status'] !== -1){
                Users::where('id',$info['id'])->update(['password' => bcrypt($password)]);
                return $this->writeJson(0,route('home.login.login'), '找回成功,请重新登录');
            }else{
                return $this->writeJson(1,null, '该用户不存在');
            }
        }else{
            return view('home.login.find_pass');
        }
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        auth()->guard('web')->logout();
        $request->session()->regenerate();
        return redirect(route('home.login.login'));
    }



    public function redirectToProvider()
    {
        return Socialite::driver('qq')->redirect();
    }

    public function handleProviderCallback()
    {
        $user = Socialite::driver('qq')->user();
        $token = $user->token;
        $refreshToken = $user->refreshToken; // not always provided
        $expiresIn = $user->expiresIn;

        // OAuth One Providers
        $token = $user->token;
        $tokenSecret = $user->tokenSecret;

        // All Providers
        $user->getId();
        $user->getNickname();
        $user->getName();
        $user->getEmail();
        $user->getAvatar();
        //如果您已拥有用户的有效访问令牌，则可以使用以下userFromToken方法检索其详细信息：
        $user = Socialite::driver('github')->userFromToken($token);
        //如果您已为用户提供了一对有效的令牌/机密，则可以使用以下userFromTokenAndSecret方法检索其详细信息
//        $user = Socialite::driver('twitter')->userFromTokenAndSecret($token, $secret);
    }

}